# -*- encoding: utf-8 -*-
# -*- coding: utf-8 -*-
import urllib.request
import json
import random
import logging
import pymysql
import copy
from flask import Flask,jsonify,request

app = Flask(__name__)#创建一个服务，赋值给APP
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route('/chat',methods=['post'])#指定接口访问的路径，支持什么请求方式get，post

def get_query():
    query = request.json.get('query')#接收json
    def chat(query):#闲聊模块
        try:
            access_token = '24.8eab2211d7c3bfb516f7f73d3b87cd6b.2592000.1535681704.282335-11616369'
            url = 'https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=' + access_token
            post_data = "{\"bot_session\":\"\",\"log_id\":\"123456\",\"request\":{\"bernard_level\":1,\"client_session\":\"{\\\"client_results\\\":\\\"\\\", \\\"candidate_options\\\":[]}\",\"query\":\" " + query + "\",\"query_info\":{\"asr_candidates\":[],\"source\":\"KEYBOARD\",\"type\":\"TEXT\"},\"updates\":\"\",\"user_id\":\"0123\"},\"bot_id\":5,\"version\":\"2.0\"}"
            post_data=post_data.encode('utf-8')
            request1 = urllib.request.Request(url, post_data)
            request1.add_header('Content-Type', 'application/json')
            response = urllib.request.urlopen(request1)
            content = response.read()
            content = content.decode('utf-8')
            content_sql = copy.deepcopy(content)
            random_num = random.randint(0,len(json.loads(content)['result']['response']['action_list'])-1)
            content_return = {'say':json.loads(content)['result']['response']['action_list'][random_num]['say']}
            if content:
                print(content)
                content_sql = eval(json.loads(content_sql)['result']['bot_session'])
                content_sql['interactions'][0]['request']['version'] = '2.0'
                content_sql['interactions'][0]['request']['bot_id'] = '5'
                insert_sql = '''INSERT INTO unit_chat(return_json)
                                           VALUES ('%s')''' % json.dumps(content_sql).replace("\\","\\\\")
                db = pymysql.connect(host='127.0.0.1',
                                     port=3306,
                                     user='root',
                                     password='123456',
                                     database='unit',
                                     charset='utf8')
                cursor = db.cursor()
                try:
                    cursor.execute(insert_sql)
                    db.commit()
                except:
                    db.rollback()
                    db.close()
                    return json.dumps({'sql_error': '数据库插入失败'})
                db.close()
                return json.dumps(content_return)
        except Exception as e:
            return json.dumps({'unit_chat_error':str(e)})


    try:
        access_token = '24.8eab2211d7c3bfb516f7f73d3b87cd6b.2592000.1535681704.282335-11616369'
        url = 'https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=' + access_token
        post_data = "{\"bot_session\":\"\",\"log_id\":\"1234567\",\"request\":{\"bernard_level\":1,\"client_session\":\"{\\\"client_results\\\":\\\"\\\", \\\"candidate_options\\\":[]}\",\"query\":\" " + query + "\",\"query_info\":{\"asr_candidates\":[],\"source\":\"KEYBOARD\",\"type\":\"TEXT\"},\"updates\":\"\",\"user_id\":\"0123\"},\"bot_id\":8932,\"version\":\"2.0\"}"
        post_data=post_data.encode('utf-8')
        request1 = urllib.request.Request(url, post_data)
        request1.add_header('Content-Type', 'application/json')
        response = urllib.request.urlopen(request1)
        content = response.read()
        content = content.decode('utf-8')
        #判断进入闲聊或识别意图并返回json
        if json.loads(content)['result']['response']['action_list'][0]['type'] == "failure":
            return chat(query)
        else:
            print(content)
            return content
    except Exception as e:
        return json.dumps({'unit_military_error': str(e)})


if __name__ == "__main__":
    app.run(threaded=True)
